import type { RouteRecordRaw } from 'vue-router';
import { cloneDeep } from 'lodash-es';
import { store } from '@/store';
import router, { completeRoutes, constantRoutes } from '@/router';

import MenuAPI, { type RouteVO } from '@/api/system/menu';

// const modules = import.meta.glob('../../views/**/**.vue');
// const Layout = () => import('@/layout/index.vue');

export const usePermissionStore = defineStore('permission', () => {
  // 所有路由，包括静态和动态路由
  const routes = ref<RouteRecordRaw[]>([]);

  // 混合模式左侧菜单路由
  const mixedLayoutLeftRoutes = ref<RouteRecordRaw[]>([]);
  // 路由是否已加载
  const isRoutesLoaded = ref(false);

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      MenuAPI.getRoutes()
        .then((res) => {
          const dynamicRoutes = transformRoutes(res.data);
          console.log('---[completeRoutes]---', completeRoutes);
          console.log('---[dynamicRoutes]---', dynamicRoutes);
          routes.value = [...constantRoutes].concat(dynamicRoutes);
          isRoutesLoaded.value = true;
          resolve(routes.value);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 根据父菜单路径设置混合模式左侧菜单
   *
   * @param parentPath 父菜单的路径，用于查找对应的菜单项
   */
  const setMixedLayoutLeftRoutes = (parentPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === parentPath);
    if (matchedItem && matchedItem.children) {
      mixedLayoutLeftRoutes.value = matchedItem.children;
    }
  };

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 删除动态路由，保留静态路由
    routes.value.forEach((route) => {
      if (route.name && !constantRoutes.find((r) => r.name === route.name)) {
        // 从 router 实例中移除动态路由
        router.removeRoute(route.name);
      }
    });

    routes.value = [];
    mixedLayoutLeftRoutes.value = [];
    isRoutesLoaded.value = false;
  };

  return {
    routes,
    generateRoutes,
    mixedLayoutLeftRoutes,
    setMixedLayoutLeftRoutes,
    isRoutesLoaded,
    resetRouter,
  };
});

/**
 * 转换路由数据为组件，将本地路由表与远程路由表对比
 */
const transformRoutes = (routes: RouteVO[], localRoutes = completeRoutes) => {
  const dynamicRoutes: RouteRecordRaw[] = [];

  localRoutes.forEach((localRoute) => {
    const tmpRoute = cloneDeep(localRoute) as RouteRecordRaw;
    const matchRoute = routes.find((r) => r.path === tmpRoute.path);
    if (!matchRoute) return;
    if (localRoute.children?.length) {
      tmpRoute.children = transformRoutes(matchRoute.children, localRoute.children);
    }
    dynamicRoutes.push(tmpRoute);
  });
  return dynamicRoutes;

  // const dynamicRoutes: RouteRecordRaw[] = [];
  // routes.forEach((route) => {
  //   const tmpRoute = { ...route } as RouteRecordRaw;
  //   // 顶级目录，替换为 Layout 组件
  //   if (tmpRoute.component?.toString() == 'Layout') {
  //     tmpRoute.component = Layout;
  //   } else {
  //     // 其他菜单，根据组件路径动态加载组件
  //     const component = modules[`../../views/${tmpRoute.component}.vue`];
  //     if (component) {
  //       tmpRoute.component = component;
  //     } else {
  //       tmpRoute.component = modules['../../views/error-page/404.vue'];
  //     }
  //   }

  //   if (tmpRoute.children) {
  //     tmpRoute.children = transformRoutes(route.children);
  //   }

  //   dynamicRoutes.push(tmpRoute);
  // });

  // return dynamicRoutes;
};

/**
 * 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
